//
//  LYPlaybackView.m
//  LYLiveApp
//
//  Created by QD on 2017/7/17.
//  Copyright © 2017年 览益信息科技. All rights reserved.
//

#import "LYPlaybackView.h"
#import "LYPlaybackModel.h"

@interface LYPlaybackView ()
{
    UITapGestureRecognizer *_showTap;
    UIPanGestureRecognizer *_panGesture;
}


@property (weak, nonatomic) IBOutlet UIView *noDataView;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property(nonatomic,assign) BOOL isLocked;
@property (assign, nonatomic) BOOL   isShowRoundView;
@property (weak, nonatomic) IBOutlet UIButton *lockBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *setViewTrailing;
@property(nonatomic,strong) UIControl *controlView;
@property (weak, nonatomic) IBOutlet UIView *setView;
@property (weak, nonatomic) IBOutlet UIView *shareView;
@property (weak, nonatomic) IBOutlet UISlider *voiceSlider;
@property (weak, nonatomic) IBOutlet UISlider *lightSlider;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *shareViewTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *setBtnTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lockBtnTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toProtaitBtnTrailing;

@end

static const NSTimeInterval kAnimationTime              = 1.5f    ;
static const CGFloat        kAdjustRateValue            = 10.0f   ;


@implementation LYPlaybackView

- (void)drawRect:(CGRect)rect {
    
    self.original = 0;

    self.fullProgressSlider.layer.cornerRadius = 2.5f;
    self.fullProgressSlider.layer.masksToBounds = YES;
    [self.fullProgressSlider setThumbImage:[UIImage imageNamed:@"video_slider"] forState:UIControlStateNormal];
    [self.fullProgressSlider addTarget:self action:@selector(_processChange:) forControlEvents:UIControlEventValueChanged];

    _showTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_showViewAction)];
    self.userInteractionEnabled = YES;
    [self addGestureRecognizer:_showTap];
    
    _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(_handleSwipe:)];
    [self addGestureRecognizer:_panGesture];

    
    self.isLocked = NO;
   
    [self.voiceSlider setThumbImage:[UIImage imageNamed:@"video_silder"] forState:UIControlStateNormal];
    self.voiceSlider.value = [VHallMoviePlayer getSysVolumeSize];
    [self.lightSlider setThumbImage:[UIImage imageNamed:@"video_silder"] forState:UIControlStateNormal];
    self.lightSlider.value = [UIScreen mainScreen].brightness;
    [self.voiceSlider addTarget:self action:@selector(voiceChange:) forControlEvents:UIControlEventValueChanged];
    [self.lightSlider addTarget:self action:@selector(lightChange:) forControlEvents:UIControlEventValueChanged];
    if (isIPhoneX) {
        self.setBtnTrailing.constant = 35;
        self.lockBtnTrailing.constant = 35;
        self.toProtaitBtnTrailing.constant = 35;
    }

}


#pragma mark ------ private Methods
- (void)_processChange:(UISlider *)slider {

    self.processValue ? self.processValue(slider.value):nil;

}

- (void)_handleSwipe:( UIPanGestureRecognizer *)panGesture {
    if (self.isLocked) return;
   
    CGFloat beginBrightness = [UIScreen mainScreen].brightness;
    CGFloat beginVoice = [VHallMoviePlayer getSysVolumeSize];
    CGFloat offsetY = [panGesture translationInView:self].y;
    CGFloat locationX = [panGesture locationInView:self].x;
    
    if (panGesture.state == UIGestureRecognizerStateEnded) {
       
        self.original = self.fullProgressSlider.value;
    }
    
    if (panGesture.state == UIGestureRecognizerStateChanged) {
      
        CGPoint translation = [panGesture translationInView:self];
        CGFloat absX = fabs(translation.x);
        CGFloat absY = fabs(translation.y);
        
        // 设置滑动有效距离
        if (MAX(absX, absY) < 10)
            return;
        
        if (absX > absY ) {
            if (translation.x<0) {
                //向左滑动
                
                if(self.original + translation.x/SCREEN_WIDTH <=0){
                    self.fullProgressSlider.value = 0.0f;
                }else
                {
                    self.fullProgressSlider.value = self.original + translation.x/SCREEN_WIDTH;
                }
                self.processValue ? self.processValue(self.fullProgressSlider.value):nil;
            }else{
                //向右滑动
                
                if(translation.x/SCREEN_WIDTH + self.original <=0){
                    self.fullProgressSlider.value = 0.0f;
                }else
                {
                    self.fullProgressSlider.value = translation.x/SCREEN_WIDTH + self.original;
                }
                self.processValue ? self.processValue(self.fullProgressSlider.value):nil;
            }
        } else if (absY > absX) {
            if (translation.y<0) {
                //向上滑动
                if (locationX <= SCREEN_WIDTH / 2.0) {   //左边
                    
                    CGFloat newBrightness = beginBrightness  + fabs(offsetY /SCREEN_HEIGHT)/kAdjustRateValue;
                    if(newBrightness > 1.0)
                    {
                        newBrightness = 1.0;
                    }
                    [UIScreen mainScreen].brightness = newBrightness;

                } else {
                    
                    CGFloat newVoice = beginVoice  + fabs(offsetY /SCREEN_HEIGHT)/kAdjustRateValue;
                    if(newVoice > 1.0)
                    {
                        newVoice = 1.0;
                    }
                    [VHallMoviePlayer setSysVolumeSize:newVoice];
                }
            }else{
                //向下滑动
                if (locationX <= SCREEN_WIDTH / 2.0) {   //左边
                   
                    CGFloat newBrightness = beginBrightness - fabs(offsetY / SCREEN_HEIGHT)/kAdjustRateValue;
                    if(newBrightness < 0.0)
                    {
                        newBrightness = 0.0;
                    }
                    [UIScreen mainScreen].brightness = newBrightness;

                } else {
                    
                    CGFloat newVoice = beginVoice - fabs(offsetY / SCREEN_HEIGHT)/kAdjustRateValue;
                    if(newVoice < 0.0)
                    {
                        newVoice = 0.0;
                    }
                    [VHallMoviePlayer setSysVolumeSize:newVoice];
                }
            }
        }
    }
}

- (void)_showViewAction {

    WS(weakSelf)
    if (!self.isShowRoundView) {
        if (self.isLocked) {
            weakSelf.lockBtn.alpha = 0;
            
        } else {
            self.topView.hidden = YES;
            self.bottomView.hidden = YES;
            weakSelf.lockBtn.alpha = 0;
            [[UIApplication sharedApplication] setStatusBarHidden:YES];

        }
    } else {
        if (self.isLocked) {
            weakSelf.lockBtn.alpha = 1;
        } else {
            self.topView.hidden = NO;
            self.bottomView.hidden = NO;
            weakSelf.lockBtn.alpha = 1;
            [[UIApplication sharedApplication] setStatusBarHidden:NO];

        }
    }
    self.isShowRoundView = !self.isShowRoundView;
}

- (void)resetViewAction {
    WS(weakSelf)
    [UIView animateWithDuration:kAnimationTime animations:^{
        weakSelf.setViewTrailing.constant   = -230;
        weakSelf.shareViewTrailing.constant = -216;
    } completion:^(BOOL finished) {
        [_controlView removeFromSuperview];
    }];
}

#pragma mark ------ event Response
- (IBAction)shareAction:(UIButton *)button {
    
    [self addSubview:self.controlView];
    [self insertSubview:self.shareView aboveSubview:self.controlView];
    [UIView animateWithDuration:kAnimationTime animations:^{
        
        if (isIPhoneX) {
            self.shareViewTrailing.constant = 30;
        } else {
            self.shareViewTrailing.constant = 0;
        }
    } completion:^(BOOL finished) {
    }];
}

- (IBAction)weChatFriendAction:(id)sender {
    
    [self shareWithType:LYShareWeixiTimeline];
}

- (IBAction)wechatAction:(id)sender {
    
    [self shareWithType:LYShareWeixiSession];

}

- (IBAction)qqZoneAction:(id)sender {
    
    [self shareWithType:LYShareQQSpace];

}

- (IBAction)sinaAction:(id)sender {
    
    if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"sinaweibo://"]]) {
        [LYUtil showFailedHUD:@"请安装新浪客户端" AddedTo:self interval:2.0];
        return;
    }
    
    [self shareWithType:LYSinaWeibo];

}

- (IBAction)qqAction:(id)sender {
    
    [self shareWithType:LYShareQQ];

}

- (void)shareWithType:(NSInteger)shareType {
   
    WS(weakSelf)
    [self resetViewAction];
    NSString *shareTitle;
    NSString *shareContent;
    NSString *shareImage;
    NSString *shareUrl;
   
    UIViewController *viewController = [self _getViewController];
    
    if (self.isVideoLivingPage) {
        shareTitle = kShareVideoTitle;
        shareContent = kShareContent;
        shareImage = kShareImgUrl;
        shareUrl = kShareVideoUrl;
    } else {
        shareTitle = self.currentPlayModel.vtitle;
        shareContent = self.currentPlayModel.vcontent;
        shareImage = self.currentPlayModel.img_url;
        shareUrl = self.currentPlayModel.link_url;
    }
    
    [LYUMShareManager UMShareTitle:shareTitle shareContent:shareContent shareImage:shareImage shareType:shareType shareUrl:shareUrl presentedController:viewController completBlock:^(id result, NSError *error) {
        if (error != nil) {
            
            NSString *shareTypeStr = nil;
            if (shareType == LYShareWeixiSession) {
                shareTypeStr = @"微信";
            } else if (shareType == LYShareWeixiTimeline) {
                shareTypeStr = @"朋友圈";
                
            } else if (shareType == LYShareQQSpace) {
                shareTypeStr = @"QQ空间";
                
            } else if (shareType == LYShareQQ) {
                shareTypeStr = @"QQ";
                
            } else if (shareType == LYSinaWeibo) {
                shareTypeStr = @"微博";
            }
            
            [[SensorsAnalyticsSDK sharedInstance] track:@"VideoReviewForward"
                                         withProperties:@{
                                                          @"ly_forward_type":[LYUtil lySensorsString:shareTypeStr],
                                                          @"ly_video_id":[LYUtil lySensorsString:weakSelf.currentPlayModel.vurl],
                                                          @"ly_video_title":[LYUtil lySensorsString:weakSelf.currentPlayModel.vtitle],
                                                          }];
            [LYUtil showSuccessHUD:@"分享成功！" AddedTo:MAIN_WINDOW interval:1.5];
        }
    }];
}

- (UIViewController *)_getViewController {
    
    for (UIView *view = self; view; view = view.superview) {
        UIResponder *nextResponder = [view nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}


- (void)voiceChange:(UISlider *)slider {
    if (self.voiceBlock) {
        self.voiceBlock(slider.value);
    }
}

- (void)lightChange:(UISlider *)slider {
    [[UIScreen mainScreen] setBrightness:slider.value];
}

- (IBAction)backAction:(id)sender {
    
    self.backBlock ? self.backBlock():nil;
    
}

- (IBAction)resetAction:(UIButton *)button {
    
    [self addSubview:self.controlView];
    [self insertSubview:self.setView aboveSubview:self.controlView];
    
    if (isIPhoneX) {
        self.setViewTrailing.constant = 30;
    } else {
        self.setViewTrailing.constant = 0;
    }
}

- (IBAction)playAction:(UIButton *)button {
    
    if (button.selected) {
        self.block ? self.block(YES):nil;
    } else {
        self.block ? self.block(NO):nil;
    }
}

- (IBAction)toSmallScreenAction:(id)sender {
    
    self.backBlock ? self.backBlock():nil;
    
}

- (IBAction)lockAction:(UIButton *)button {
   
    button.selected = !button.selected;
    if (self.lockBlock) {
        self.lockBlock(button.selected);
    }

     if (button.selected) {
         self.isLocked = YES;
        self.lockBlock ? self.lockBlock(YES):nil;
         self.topView.hidden = YES;
         self.bottomView.hidden = YES;

    } else {
        self.isLocked = NO;
        self.lockBlock ? self.lockBlock(NO):nil;
        self.topView.hidden = NO;
        self.bottomView.hidden = NO;

    }
}

#pragma mark ----- getters and setters
- (UIControl *)controlView {
    
    if (nil == _controlView) {
        _controlView = [[UIControl alloc] init];
        _controlView.frame = self.frame;
        _controlView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resetViewAction)];
        [_controlView addGestureRecognizer:tap];
        _controlView.backgroundColor = [UIColor clearColor];
    }
    return _controlView;
}


+ (instancetype)viewWithXib
{
    LYPlaybackView *view = [[[UINib nibWithNibName:@"LYPlaybackView" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
    return view;
}
@end
